package com.studyjava.guessdx;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class choosepic extends AppCompatActivity {

    private TextView textViewIdStr;
    private GridLayout imageGrid;
    private int correctId;
    private String correctStr;
    private String correctFileName;
    private int userScore;  // 用户积分
    private TextView scoreTextView;  // 显示积分的文本框
    private Button skipButton;  // 跳过按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_pic);

        textViewIdStr = findViewById(R.id.textView);
        scoreTextView = findViewById(R.id.scoreTextView);
        skipButton = findViewById(R.id.skipButton);
        imageGrid = findViewById(R.id.gridLayout);

        // 加载用户的积分
        loadUserScore();

        // 设置跳过按钮点击事件
        skipButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadAndDisplayImages();  // 跳过当前问题，加载新问题
            }
        });

        // 使用 ViewTreeObserver 确保布局加载完成后再设置子项大小
        ViewTreeObserver viewTreeObserver = imageGrid.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    imageGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    loadAndDisplayImages();
                }
            });
        }
    }

    private void parseXMLAndSetTextView() {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xpp = factory.newPullParser();
            InputStream inputStream = getAssets().open("MusicSort.xml");
            xpp.setInput(inputStream, null);

            List<Integer> ids = new ArrayList<>();
            List<String> strs = new ArrayList<>();
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tag = xpp.getName();
                if (eventType == XmlPullParser.START_TAG && "id".equals(tag)) {
                    ids.add(Integer.parseInt(xpp.nextText()));
                } else if (eventType == XmlPullParser.START_TAG && "str".equals(tag)) {
                    strs.add(xpp.nextText());
                }
                eventType = xpp.next();
            }
            inputStream.close();

            Random random = new Random();
            int randomIndex = random.nextInt(ids.size());
            correctId = ids.get(randomIndex);
            correctStr = strs.get(randomIndex);

            textViewIdStr.setText("ID: " + correctId + "\nStr: " + correctStr);

            correctFileName = String.format("UI_Jacket_%06d.png", correctId > 9999 ? correctId - 10000 : correctId);
        } catch (IOException | XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    private void loadAndDisplayImages() {
        parseXMLAndSetTextView();

        imageGrid.removeAllViews();

        List<String> imageFiles = new ArrayList<>();
        try {
            String[] files = getAssets().list("music_pic");
            for (String file : files) {
                if (file.startsWith("UI_Jacket_")) {
                    imageFiles.add(file);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        imageFiles.remove(correctFileName);
        Collections.shuffle(imageFiles);
        int correctImagePosition = (int) (Math.random() * 9);
        imageFiles.add(correctImagePosition, correctFileName);

        imageGrid.setColumnCount(3);
        int gridWidth = imageGrid.getWidth();

        for (int i = 0; i < 9; i++) {
            final String imageName = imageFiles.get(i);
            ImageView imageView = new ImageView(this);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            int imageSize = gridWidth / 3;
            layoutParams.width = imageSize;
            layoutParams.height = imageSize;
            layoutParams.setMargins(0, 0, 0, 0);
            imageView.setLayoutParams(layoutParams);
            imageView.setImageBitmap(loadImageFromAssets("music_pic/" + imageName));

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (imageName.equals(correctFileName)) {
                        userScore += 3;  // 答对加3分
                        saveUserScore();  // 保存积分
                        loadAndDisplayImages();  // 加载新问题
                    } else {
                        userScore -= 1;  // 答错扣1分
                        saveUserScore();  // 保存积分
                        Toast.makeText(choosepic.this, "错误，请再试一次！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            imageGrid.addView(imageView);
        }
    }

    // 从文件中加载用户积分
    private void loadUserScore() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG && "Score".equals(tagName)) {
                    userScore = Integer.parseInt(parser.nextText());
                }
                eventType = parser.next();
            }
            inputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存用户积分到文件中
    private void saveUserScore() {
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");
            serializer.startTag(null, "Score");
            serializer.text(String.valueOf(userScore));
            serializer.endTag(null, "Score");
            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新积分显示
    private void updateScoreDisplay() {
        scoreTextView.setText("当前积分: " + userScore);
    }

    private Bitmap loadImageFromAssets(String fileName) {
        try {
            InputStream is = getAssets().open(fileName);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);
            is.close();
            options.inSampleSize = calculateInSampleSize(options, imageGrid.getWidth() / 3, imageGrid.getWidth() / 3);
            is = getAssets().open(fileName);
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            is.close();
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = Math.min(heightRatio, widthRatio);
        }

        return inSampleSize;
    }
}
